package com.weather.MQTT.callBack;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weather.domain.Weather;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * @author 化粪池堵塞的凶手
 */
public class MyMqttCallBack implements MqttCallback {
    private MqttClient client;

    private Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    public MyMqttCallBack(MqttClient client) {
        this.client = client;
    }

    /**
     * 重连
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        logger.warn("***** MQTT connect Lost *****");
        while (true){
            if (!client.isConnected()){
                logger.warn("***** MQTT reConnect *****");
                try {
                    Thread.sleep(3000);
                    client.reconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            else {
                logger.warn("***** MQTT reConnect success *****");
                break;
            }
        }
    }


    /**
     * 接收信息
     * @param s
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        byte[] payload = mqttMessage.getPayload();
        String message = new String(payload);
        logger.info("***** MQTT Get Message *****");
        logger.info("id:"+mqttMessage.getId());
        logger.info("message:"+ message);
        JsonNode jsonNode = new ObjectMapper().readTree(message);
        //获取name字段值
        JsonNode name = jsonNode.get("name");
        String s2 = name.asText();
        System.out.println(s2);
        /**
         * 数据库插入信息,封装成一个Weather对象
         */


    }


    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("send");
    }
}
